const router = require("koa-router")();
const { register, login } = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../res-model/index");
router.prefix("/api/user");

//注册
router.post("/register", async (ctx, next) => {
  const { username, password } = ctx.request.body;
  //新建用户

  try {
    const newUser = await register(username, password);

    
    ctx.body = new SuccessModel(newUser);
  } catch (error) {
    console.log(error);
    ctx.body = new ErrorModel(10001, `注册失败-${error.message}`);
  }
});

//登录
router.post("/login", async (ctx, next) => {
  const { username, password } = ctx.request.body;
  //查询单个用户
  const res = await login(username, password);

  
  if (res) {
    //登录成功
    ctx.session.userInfo={username} //设置session

    ctx.body = new SuccessModel();
  } else {
    ctx.body = new ErrorModel(10002, `登录验证失败`);
  }
});
module.exports = router;
